package com.example.sharding.common.shardingjdbc.algorithm;

import com.google.common.collect.Lists;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class IdRangeShardingAlgorithm implements RangeShardingAlgorithm<String> {
    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<String> rangeShardingValue) {
            Set<String> result = new LinkedHashSet<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
            // between and 的起始值
            String lower = sdf.format(rangeShardingValue.getValueRange().lowerEndpoint());
            String upper = sdf.format(rangeShardingValue.getValueRange().upperEndpoint());

            List<String> timeList = packDateStrListByInterval(Integer.parseInt(lower.substring(lower.length()-2)), Integer.parseInt(upper.substring(upper.length()-2)));
            // 循环范围计算分表逻辑
            for(String time : timeList){
                result.add("user"+time);
            }
            return result;
        }

        //与Demo的业务相关，不需要具体看清该业务逻辑，只要知道doSharding方法时用于筛选除需要进行查询的所有表即可
        private List<String> packDateStrListByInterval(int start, int end) {
            List<String> list = Lists.newArrayList();
            if (end>=start){
                int z=start;
                start=end;
                end=z;
            }
            for (int i = start; i <= end; i++){
                list.add(i%2+"");
            }
            return list;
        }
    }

